package fi.helsinki.cs.ohtu10k.view;

import javax.swing.*;

import java.awt.event.*;
import java.awt.Frame;
import com.sun.java.layout.SpringUtilities;
import org.joda.time.DateTime;

import fi.helsinki.cs.ohtu10k.schedule.ScheduleEvent;
import fi.helsinki.cs.ohtu10k.schedule.ScheduleManagerHandler;


/**
 * Class implementing event deletion dialog.
 * @author Hannu Kärnä
 * @author Thomas Nyman
 *
 */
@SuppressWarnings("serial")
public class DeleteEventDialog extends JDialog implements ActionListener {
	
	private JPanel panel;
	private JButton buttonDeleteEvent, buttonCancel;
	private JComboBox selectorEvent;
	
	/**
	 * Display a delete event dialog.
	 * @param owner Owning frame.
	 * @param startDate Start date of period from which offer events for deletion.
	 * @param endDate End date of period from which offer events for deletion.
	 */
	public static void showDeleteEventDialog(Frame owner, DateTime startDate, DateTime endDate) {
		ScheduleEvent[] events = ScheduleManagerHandler.getScheduleManager().getEvents(startDate, endDate);
		
		if(events.length == 0) 
    		JOptionPane.showMessageDialog(owner,
    									  Constants.LABEL_ERROR_NO_EVENTS,
    									  Constants.LABEL_DELETE_EVENT_TITLE,
    									  JOptionPane.PLAIN_MESSAGE);
    	else {
    		new DeleteEventDialog(owner, events);
    	}
	}
	
	/**
	 * Creates new delete event dialog.
	 * @param owner Owning frame.
	 * @param events Events to offer for deletion.
	 */
	public DeleteEventDialog(Frame owner, ScheduleEvent[] events) {
		super(owner, Constants.LABEL_DELETE_EVENT, true);
	
		panel = new JPanel();
		panel.setLayout(new SpringLayout());
		
		// Initialization of interactive components.
		selectorEvent = new JComboBox(events);
		buttonDeleteEvent = new JButton(Constants.LABEL_DELETE_EVENT);
		buttonCancel = new JButton(Constants.LABEL_CANCEL);
		
		// Add components to panel.
		panel.add(new JLabel(Constants.LABEL_DELETE_EVENT_SELECT));
		panel.add(selectorEvent);
		panel.add(new JPanel());
		panel.add(new JPanel());
		panel.add(buttonDeleteEvent);
		panel.add(buttonCancel);
		
		buttonDeleteEvent.addActionListener(this);
		buttonCancel.addActionListener(this);
		
		// Build compact layout
		SpringUtilities.makeCompactGrid(panel,
                						3, 2,	//rows, columns
                						18, 12,	//initX, initY
                						18, 12);//xPad, yPad
		
		this.setContentPane(panel);
		pack();
        setLocationRelativeTo(owner);
        setVisible(true);
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource()==buttonDeleteEvent) {
			ScheduleManagerHandler.getScheduleManager().delEvent((ScheduleEvent)selectorEvent.getSelectedItem());
		}
		setVisible(false);
    }
		
}
